package com.axzhengxin.platform.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.axzhengxin.platform.business.domain.*;
import com.axzhengxin.platform.business.mapper.*;
import com.axzhengxin.platform.business.service.IBizLoanInfoService;
import com.axzhengxin.platform.common.util.IdUtils;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author AHZJ0005
 * @Date 2021/2/24-9:31
 **/
@Slf4j
@Service
public class BizLoanInfoServiceImpl implements IBizLoanInfoService {
    @Autowired
    private BizApplyInfoMapper bizApplyInfoMapper;
    @Autowired
    private BizApproveInfoMapper bizApproveInfoMapper;
    @Autowired
    private BizLoanInfoMapper bizLoanInfoMapper;
    @Autowired
    private BizRepaymentInfoMapper bizRepaymentInfoMapper;

    @Autowired
    private BizFlowInfoMapper flowInfoMapper;
    @Autowired
    private BizFlowTaskMapper flowTaskMapper;

    @Autowired
    private SysUserMapper userMapper;
    @Value("${systemConfig.ahjr_service_url:#{null}}")
    private String ahjr_service_url;

    @Autowired
    private IdUtils idUtils;

    @Override
    @DataScope(deptAlias = "biz_flow")
    public List<BizApplyInfo> list(BizApplyInfo applyInfo) {
        List<BizApplyInfo> bizApplyInfos = bizApplyInfoMapper.selectBizApplyInfoList(applyInfo);
        /*if (bizApplyInfos != null && bizApplyInfos.size() > 0) {
            BigDecimal sum = new BigDecimal(0);
            for (BizApplyInfo bizApplyInfo : bizApplyInfos) {
                String reqId = bizApplyInfo.getReqId();
                BizApproveInfo bizApproveInfo = bizApproveInfoMapper.selectBizApproveInfoByReqId(reqId);
                if (bizApproveInfo!=null) {
                    List<BizApproveDetail> detailList = bizApproveInfo.getDetailList();
                    if (detailList != null && detailList.size() > 0) {
                        for (BizApproveDetail bizApproveDetail : detailList) {
                            BigDecimal approveAmount = bizApproveDetail.getApproveAmount();
                            sum = sum.add(approveAmount);
                        }
                    }
                    String sumAmount = String.valueOf(sum);
                    String[] split = sumAmount.split("\\.");
                    if (split != null && split.length > 0) {
                        bizApproveInfo.setSumApproveAmount(split[0]);
                    } else {
                        bizApproveInfo.setSumApproveAmount("0");
                    }
                }
                bizApplyInfo.setBizApproveInfo(bizApproveInfo);
            }
        }*/
        return bizApplyInfos;
    }

    /**
     * @param bizLoanInfo
     * @return 101-放款额度设置过大
     */
    @Override
    public AjaxResult insertLoanInfo(BizLoanInfo bizLoanInfo) {
        //添加前判断金额是否超过授信金额
        boolean flag = false;
        String applyId = bizLoanInfo.getApplyId();
        BizApplyInfo bizApplyInfo = bizApplyInfoMapper.selectBizApplyInfoById(applyId);
        BigDecimal loanAmount = bizLoanInfo.getLoanAmount();
        String approveId = bizLoanInfo.getApproveId();
        Map<String, Object> map = new HashMap<>();
        map.put("approveId", approveId);
        map.put("loanAmount", loanAmount);
        Map<String, Object> resultMap = bizLoanInfoMapper.checkLoanAmountByApproveId(map);

        BigDecimal approveAmount = (BigDecimal) resultMap.get("approveAmount");
        if (!resultMap.containsKey("canDeal")) {
            if (loanAmount.compareTo(approveAmount) > 0) {
                return AjaxResult.error("放款金额设置过大，当前最大仅设置为" + approveAmount.setScale(2, RoundingMode.HALF_UP) + "万元");
            }

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("reqNo", applyId);
            jsonObject1.put("flag", "1");

            String loanType = "3";
            BizApproveInfo bizApproveInfo1 = bizApproveInfoMapper.selectBizApproveInfoByApproveId(bizLoanInfo.getApproveId());
            String creditAmount = bizApproveInfo1.getApproveAmount().toPlainString();
            if (null != creditAmount && !"".equals(creditAmount)) {
                BigDecimal bigDecimal = new BigDecimal(creditAmount);
                bigDecimal = bigDecimal.multiply(new BigDecimal(10000));
                creditAmount = bigDecimal.toPlainString();
            }
            jsonObject1.put("contractNo", bizLoanInfo.getLoanContractNo());
            jsonObject1.put("guaranteeType", loanType);
            jsonObject1.put("guaranteeRatio", "0");
            //warn.getDelay()  放款利率
            jsonObject1.put("delay", bizLoanInfo.getLoanRatio());
            jsonObject1.put("amt", creditAmount);
            jsonObject1.put("operationTime", new Date());
            jsonObject1.put("isFirstLoan", bizApproveInfo1.getIfFirstApprove());
            jsonObject1.put("startDate", bizLoanInfo.getLoanStart());
            jsonObject1.put("endDate", bizLoanInfo.getLoanEnd());
            //0-非应急贷款,1-应急贷款
            jsonObject1.put("isLoan", "0");

            JSONObject jo = JSON.parseObject(jsonObject1.toJSONString());
            String loanAmountz = bizLoanInfo.getLoanAmount().toPlainString();
            if (StringUtils.isNotBlank(loanAmountz)) {
                BigDecimal bigDecimal = new BigDecimal(loanAmountz);
                bigDecimal = bigDecimal.multiply(new BigDecimal(10000));
                loanAmountz = bigDecimal.toPlainString();
            }
            jo.put("amt", loanAmountz);
            jo.put("flag", "2");
            System.out.println("=====================开始调用放款接口======================");
            JSONObject credit = ahjrService(jo, "credit");
            Integer code = (Integer) credit.get("code");
            if (200 != code) {
                System.out.println("*************中小微平台数据更新失败*************");
                System.out.println(credit.get("msg"));
                System.out.println("*************中小微平台数据更新失败************");
                return AjaxResult.error("中小微平台数据更新失败:" + credit.get("msg"));
            }
            //等于的时候则表示放款流程结束
            if (loanAmount.compareTo(approveAmount) == 0) {
                SysUser user = SecurityUtils.getLoginUser().getUser();
                String userID = String.valueOf(user.getUserId());
                updateFlowInfoBizTypeAndStatus(2000, "LOAN", bizLoanInfo.getFlowUid(), userID);

                BizFlowTask bizFlowTask = new BizFlowTask();
                bizFlowTask.setUserId(userID);
                bizFlowTask.setCreateBy(userID);
                bizFlowTask.setCreateTime(new Date());
                bizFlowTask.setFlowUid(bizLoanInfo.getFlowUid());
                bizFlowTask.setBizType("LOAN");
                bizFlowTask.setStatus(2000);
                flowTaskMapper.updateByFlowUid(SecurityUtils.getLoginUser().getUser().getUserId().toString(), bizLoanInfo.getFlowUid());
                flowTaskMapper.insertBizFlowTask(bizFlowTask);
                flag = true;
            }
        } else {
            BigDecimal canDeal = (BigDecimal) resultMap.get("canDeal");
            BigDecimal result = (BigDecimal) resultMap.get("result");
            boolean b = result.compareTo(new BigDecimal(-1)) == 0;
            if (!b) {
                return AjaxResult.error("放款金额设置过大，当前最大仅设置为" + canDeal.setScale(2, RoundingMode.HALF_UP) + "万元");

            }
            //等于的时候则表示放款流程结束
            if (loanAmount.compareTo(canDeal) == 0) {
                SysUser user = SecurityUtils.getLoginUser().getUser();
                String userID = String.valueOf(user.getUserId());
                updateFlowInfoBizTypeAndStatus(2000, "LOAN", bizLoanInfo.getFlowUid(), userID);

                BizFlowTask bizFlowTask = new BizFlowTask();
                bizFlowTask.setUserId(userID);
                bizFlowTask.setCreateBy(userID);
                bizFlowTask.setCreateTime(new Date());
                bizFlowTask.setFlowUid(bizLoanInfo.getFlowUid());
                bizFlowTask.setBizType("LOAN");
                bizFlowTask.setStatus(2000);
                flowTaskMapper.updateByFlowUid(SecurityUtils.getLoginUser().getUser().getUserId().toString(), bizLoanInfo.getFlowUid());
                flowTaskMapper.insertBizFlowTask(bizFlowTask);
                flag = true;
            }

        }
        String snakeId = idUtils.getSnakeId();
        bizLoanInfo.setLoanId(snakeId);
        bizLoanInfo.setCreateTime(new Date());
        bizLoanInfo.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUser().getUserId()));
        bizLoanInfo.setCustomerId(bizApplyInfo.getCustomerId());
        bizLoanInfo.setCustomerName(bizApplyInfo.getCustomerName());
        bizLoanInfoMapper.insertBizLoanInfo(bizLoanInfo);
        if (flag) {
            return AjaxResult.success("当前订单放款已全部完成！");
        }
        return AjaxResult.success("新增放款成功！");
    }

    @Override
    public int insertRepaymentInfo(BizRepaymentInfo bizRepaymentInfo) {
        return bizRepaymentInfoMapper.insertBizRepaymentInfo(bizRepaymentInfo);
    }

    /**
     * 首先判断还款金额是否超出未还放款金额
     *
     * @param bizRepaymentInfo 还款对象
     * @return 结果集
     */
    @Override
    public AjaxResult insertRepaymentInfoVo(BizRepaymentInfo bizRepaymentInfo) {
        //查询出已还总额
        BizLoanInfo bizLoanInfo = bizLoanInfoMapper.selectBizLoanInfoById(bizRepaymentInfo.getLoanId());
        bizRepaymentInfo.setLoanContractNo(bizLoanInfo.getLoanContractNo());
        bizRepaymentInfo.setCustomerId(bizLoanInfo.getCustomerId());
        bizRepaymentInfo.setApplyId(bizLoanInfo.getApplyId());
        BigDecimal repayment = bizRepaymentInfoMapper.selectBizRepaymentInfoLoanId(bizRepaymentInfo.getLoanId());
        if (repayment == null) {
            repayment = new BigDecimal(0);
        }
        BigDecimal loanAmount = bizLoanInfo.getLoanAmount();
        BigDecimal subtract = loanAmount.subtract(repayment);
        if (bizRepaymentInfo.getRepaymentAmount().compareTo(subtract) > 0) {
            return AjaxResult.error("还款金额设置过大,当前未还金额为" + subtract.setScale(2, RoundingMode.HALF_UP) + "万元");
        }
        bizRepaymentInfo.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUser().getUserId()));
        bizRepaymentInfo.setRepaymentId(idUtils.getSnakeId());
        bizRepaymentInfo.setCreateTime(new Date());
        bizRepaymentInfoMapper.insertBizRepaymentInfo(bizRepaymentInfo);
        return AjaxResult.success();
    }

    @Override
    public List<BizLoanInfo> bizLoanInfoList(String reqId) {
        Long deptId = SecurityUtils.getLoginUser().getUser().getDeptId();

        return bizLoanInfoMapper.bizLoanInfoList(reqId, String.valueOf(deptId));
    }

    @Override
    public BizLoanInfo getLoanInfo(String loanId) {

        return bizLoanInfoMapper.selectBizLoanInfoById(loanId);
    }


    public void updateFlowInfoBizTypeAndStatus(Integer status, String bizType, String flowUid, String userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", status);
        map.put("bizType", bizType);
        map.put("flowUid", flowUid);
        map.put("userId", userId);
        flowInfoMapper.updateFlowInfoBizTypeAndStatus(map);
    }


    public JSONObject ahjrService(JSONObject jsonObject, String serviceid) {
        System.out.println("===============开始执行与中小微平台交互接口: [" + serviceid + "]  =======================");
        Long userId = null;
        SysUser user = null;
        try {
            userId = SecurityUtils.getLoginUser().getUser().getUserId();
        } catch (Exception e) {

        }

        if (null != userId) {
            user = userMapper.selectUserById(userId);
        }
        String url = ahjr_service_url + serviceid;

        jsonObject.put("financeId", null == userId ? "000000" : user.getDept().getFinanceId());
        jsonObject.put("channel", "zxfwzx");
        jsonObject.put("contractNo", "1");
        jsonObject.put("loanContractNo", "1");
        System.out.println("==============交互请求报文=============");
        System.out.println(jsonObject.toJSONString());

        String resultStr = "";
        try {
            String jsonString = JSONObject.toJSONString(jsonObject);
            resultStr = HttpUtils.sendPost(url, jsonString, "application/json");
            System.out.println("==============交互响应报文=============");
            System.out.println(resultStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (resultStr != null) {
            JSONObject object = JSONObject.parseObject(resultStr);

            return object;
        }
        return null;
    }

}
